import React, { useState, useRef, useEffect } from 'react'
import { Button, Dialog, TextArea, Toast } from 'antd-mobile'
import { MessageOutline, CloseOutline } from 'antd-mobile-icons'
import { callQwenAPI, processFitnessQuery, testBackendConnection } from '../../services/qwenApi'
import type { QwenMessage } from '../../services/qwenApi'
import './AICoach.css'

interface AICoachProps {
  className?: string
}

const AICoach: React.FC<AICoachProps> = ({ className }) => {
  const [isDragging, setIsDragging] = useState(false)
  const [position, setPosition] = useState({ x: window.innerWidth - 80, y: window.innerHeight - 150 })
  const [isDialogVisible, setIsDialogVisible] = useState(false)
  const [messages, setMessages] = useState<Array<{ id: number; text: string; isUser: boolean; timestamp: number }>>([
    { id: 1, text: '嘿兄弟！我是小健 😎 你的直球AI朋友！\n\n不废话，直接说：我啥都能聊，而且说话超级直接！\n\n别指望我说那些没用的鸡汤，我会用最搞笑、最犀利的方式给你建议！\n\n来吧，有啥问题直接说，我保证让你笑出声！', isUser: false, timestamp: Date.now() }
  ])
  const [inputText, setInputText] = useState('')
  const [isTyping, setIsTyping] = useState(false)
  const [isLoading, setIsLoading] = useState(false)
  
  const ballRef = useRef<HTMLDivElement>(null)
  const messagesRef = useRef<HTMLDivElement>(null)
  const dragStart = useRef({ x: 0, y: 0 })
  const positionStart = useRef({ x: 0, y: 0 })
  const touchStartTime = useRef(0)
  const hasMoved = useRef(false)

  // 处理触摸开始事件
  const handleTouchStart = (e: React.TouchEvent) => {
    e.stopPropagation()
    const touch = e.touches[0]
    touchStartTime.current = Date.now()
    hasMoved.current = false
    setIsDragging(true)
    dragStart.current = { x: touch.clientX, y: touch.clientY }
    positionStart.current = { x: position.x, y: position.y }
  }

  // 处理鼠标按下事件（桌面端）
  const handleMouseDown = (e: React.MouseEvent) => {
    e.preventDefault()
    e.stopPropagation()
    setIsDragging(true)
    dragStart.current = { x: e.clientX, y: e.clientY }
    positionStart.current = { x: position.x, y: position.y }
  }

  // 处理触摸移动事件
  const handleTouchMove = (e: TouchEvent) => {
    if (!isDragging) return
    e.preventDefault() // 防止页面滚动
    const touch = e.touches[0]
    
    const deltaX = touch.clientX - dragStart.current.x
    const deltaY = touch.clientY - dragStart.current.y
    
    const newX = Math.max(0, Math.min(window.innerWidth - 60, positionStart.current.x + deltaX))
    const newY = Math.max(0, Math.min(window.innerHeight - 60, positionStart.current.y + deltaY))
    
    setPosition({ x: newX, y: newY })
  }

  // 处理鼠标移动事件（桌面端）
  const handleMouseMove = (e: MouseEvent) => {
    if (!isDragging) return
    
    const deltaX = e.clientX - dragStart.current.x
    const deltaY = e.clientY - dragStart.current.y
    
    const newX = Math.max(0, Math.min(window.innerWidth - 60, positionStart.current.x + deltaX))
    const newY = Math.max(0, Math.min(window.innerHeight - 60, positionStart.current.y + deltaY))
    
    setPosition({ x: newX, y: newY })
  }

  // 处理触摸结束事件
  const handleTouchEnd = () => {
    setIsDragging(false)
  }

  // 处理鼠标释放事件（桌面端）
  const handleMouseUp = () => {
    setIsDragging(false)
  }

  // 添加全局事件监听器
  useEffect(() => {
    if (isDragging) {
      // 使用非被动模式，允许preventDefault
      document.addEventListener('touchmove', handleTouchMove, { passive: false })
      document.addEventListener('touchend', handleTouchEnd, { passive: true })
      document.addEventListener('mousemove', handleMouseMove)
      document.addEventListener('mouseup', handleMouseUp)
    }

    return () => {
      document.removeEventListener('touchmove', handleTouchMove)
      document.removeEventListener('touchend', handleTouchEnd)
      document.removeEventListener('mousemove', handleMouseMove)
      document.removeEventListener('mouseup', handleMouseUp)
    }
  }, [isDragging])

  // 处理悬浮球点击
  const handleBallClick = (e: React.MouseEvent) => {
    e.stopPropagation()
    if (!isDragging) {
      setIsDialogVisible(true)
    }
  }

  // 处理触摸点击
  const handleTouchClick = (e: React.TouchEvent) => {
    e.stopPropagation()
    const touchDuration = Date.now() - touchStartTime.current
    
    // 如果触摸时间很短且没有移动，认为是点击
    if (touchDuration < 300 && !hasMoved.current && !isDragging) {
      setIsDialogVisible(true)
    }
  }

  // 发送消息
  const handleSendMessage = async () => {
    if (!inputText.trim() || isLoading) return

    const userMessage = { id: Date.now(), text: inputText, isUser: true, timestamp: Date.now() }
    setMessages(prev => [...prev, userMessage])
    const currentInput = inputText.trim()
    setInputText('')
    setIsTyping(true)
    setIsLoading(true)

    try {
      // 构建对话历史
      const conversationHistory: QwenMessage[] = messages
        .filter(msg => !msg.isUser) // 只取AI的消息
        .slice(-5) // 只取最近5条AI消息
        .map(msg => ({
          role: 'assistant' as const,
          content: msg.text
        }))

      // 添加当前用户消息
      conversationHistory.push({
        role: 'user',
        content: processFitnessQuery(currentInput)
      })

      // 调用Qwen-Plus API
      const aiResponse = await callQwenAPI(conversationHistory)
      
      const aiMessage = { 
        id: Date.now() + 1, 
        text: aiResponse, 
        isUser: false, 
        timestamp: Date.now() 
      }
      
      setMessages(prev => [...prev, aiMessage])
    } catch (error) {
      console.error('API调用失败:', error)
      
      // 显示错误提示
      Toast.show({
        content: '抱歉，AI教练暂时无法回复，请稍后再试',
        duration: 2000,
      })
      
      // 添加错误消息
      const errorMessage = { 
        id: Date.now() + 1, 
        text: '抱歉，我暂时无法回复你的消息。请检查网络连接或稍后再试。😅', 
        isUser: false, 
        timestamp: Date.now() 
      }
      setMessages(prev => [...prev, errorMessage])
    } finally {
      setIsTyping(false)
      setIsLoading(false)
    }
  }

  // 自动滚动到底部
  const scrollToBottom = () => {
    if (messagesRef.current) {
      messagesRef.current.scrollTop = messagesRef.current.scrollHeight
    }
  }

  // 当消息更新时自动滚动
  useEffect(() => {
    scrollToBottom()
  }, [messages, isTyping])

  // 测试API连接
  const handleTestAPI = async () => {
    try {
      setIsLoading(true)
      
      // 先测试后端连接
      const backendConnected = await testBackendConnection()
      if (!backendConnected) {
        throw new Error('后端服务未启动，请先启动后端服务器')
      }
      
      const testMessage = { id: Date.now(), text: '你好，测试一下API连接', isUser: true, timestamp: Date.now() }
      setMessages(prev => [...prev, testMessage])
      
      const response = await callQwenAPI([{ role: 'user', content: '你好' }])
      const aiMessage = { id: Date.now() + 1, text: response, isUser: false, timestamp: Date.now() }
      setMessages(prev => [...prev, aiMessage])
      
      Toast.show({
        content: 'API连接成功！',
        duration: 2000,
      })
    } catch (error) {
      console.error('API测试失败:', error)
      const errorMessage = error instanceof Error ? error.message : 'API连接失败，请检查后端服务'
      Toast.show({
        content: errorMessage,
        duration: 3000,
      })
    } finally {
      setIsLoading(false)
    }
  }

  // 清空对话
  const handleClearMessages = () => {
    setMessages([
      { id: 1, text: '嘿兄弟！我是小健 😎 你的直球AI朋友！\n\n不废话，直接说：我啥都能聊，而且说话超级直接！\n\n别指望我说那些没用的鸡汤，我会用最搞笑、最犀利的方式给你建议！\n\n来吧，有啥问题直接说，我保证让你笑出声！', isUser: false, timestamp: Date.now() }
    ])
    Toast.show({
      content: '对话已清空，重新开始吧！',
      duration: 1000,
    })
  }

  // 关闭对话框
  const handleCloseDialog = () => {
    setIsDialogVisible(false)
  }

  return (
    <>
      {/* AI教练悬浮球 */}
      <div
        ref={ballRef}
        className={`ai-coach-ball ${isDragging ? 'dragging' : ''} ${className || ''}`}
        style={{
          left: position.x,
          top: position.y,
        }}
        onMouseDown={handleMouseDown}
        onTouchStart={handleTouchStart}
        onClick={handleBallClick}
        onTouchEnd={handleTouchClick}
      >
        <div className="ai-coach-avatar">
          <MessageOutline fontSize={24} />
        </div>
        <div className="ai-coach-pulse"></div>
      </div>

      {/* AI教练对话框 */}
      <Dialog
        visible={isDialogVisible}
        onClose={handleCloseDialog}
        title={
          <div className="ai-coach-dialog-header">
            <div className="ai-coach-dialog-title">
              <MessageOutline fontSize={20} />
              <span>小健 - 直球AI朋友</span>
            </div>
            <div className="ai-coach-dialog-actions">
              <Button
                fill="none"
                size="mini"
                onClick={handleTestAPI}
                style={{ color: 'white', marginRight: '4px' }}
                disabled={isLoading}
              >
                测试
              </Button>
              <Button
                fill="none"
                size="mini"
                onClick={handleClearMessages}
                style={{ color: 'white', marginRight: '4px' }}
              >
                清空
              </Button>
              <Button
                fill="none"
                size="mini"
                onClick={handleCloseDialog}
              >
                <CloseOutline fontSize={16} />
              </Button>
            </div>
          </div>
        }
        content={
          <div className="ai-coach-dialog-content">
            <div className="ai-coach-messages" ref={messagesRef}>
              {messages.map((message) => (
                <div
                  key={message.id}
                  className={`ai-coach-message ${message.isUser ? 'user-message' : 'ai-message'}`}
                >
                  <div className="message-content">
                    <div className="message-text">
                      {message.text.split('\n').map((line, index) => (
                        <div key={index}>{line}</div>
                      ))}
                    </div>
                    <div className="message-time">
                      {new Date(message.timestamp).toLocaleTimeString('zh-CN', { 
                        hour: '2-digit', 
                        minute: '2-digit' 
                      })}
                    </div>
                  </div>
                </div>
              ))}
              {isTyping && (
                <div className="ai-coach-message ai-message">
                  <div className="message-content typing">
                    <span></span>
                    <span></span>
                    <span></span>
                  </div>
                </div>
              )}
            </div>
            <div className="ai-coach-input">
              <TextArea
                value={inputText}
                onChange={setInputText}
                placeholder="输入你的问题..."
                rows={2}
                maxLength={200}
              />
              <Button
                color="primary"
                size="small"
                onClick={handleSendMessage}
                disabled={!inputText.trim() || isLoading}
                loading={isLoading}
              >
                {isLoading ? '发送中...' : '发送'}
              </Button>
            </div>
          </div>
        }
        closeOnMaskClick={false}
      />
    </>
  )
}

export default AICoach
